import Vue from 'vue'
import Vuex from 'vuex'
import { login, logout, editPassword } from '@/api/user'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户信息
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
    // 用户token
    token: localStorage.getItem('token') || ''
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    // 清除用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
      state.token = ''
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 用户登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            const { data } = response
            // 保存用户信息和token
            commit('SET_USER_INFO', {
              id: data.id,
              username: data.username,
              name: data.name,
              role: userInfo.role === 0 ? 'student' : userInfo.role === 1 ? 'teacher' : 'admin',
              avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            })
            commit('SET_TOKEN', data.token)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 退出登录
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(response => {
            commit('CLEAR_USER_INFO')
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 修改密码
    editPassword(_, data) {
      return new Promise((resolve, reject) => {
        editPassword(data)
          .then(response => {
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    }
  },
  getters: {
    // 获取用户信息
    getUserInfo: state => state.userInfo,
    // 获取用户角色
    getUserRole: state => state.userInfo.role,
    // 获取token
    getToken: state => state.token,
    // 判断用户是否已登录
    isLoggedIn: state => !!state.token
  }
})